package com.foreknow.controller;

import com.foreknow.bean.User;
import com.foreknow.service.UserService;
import com.foreknow.service.UserServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Servlet:服务器端的应用程序,主要用于处理客户端的需求
 * 1.继承HttpServlet(继承之前一定要将servlet-api.jar包放到lib文件夹中)
 * 2.重写HttpServlet中doGet/doPost方法
 * 3.HttpServletRequest req 请求对象(接口):它可以封装一些请求的信息(例如:请求的参数)
 * 4.HttpServletResponse resp 响应对象(接口):它可以实现资源跳转
 * 5.Servlet写完之后,到web.xml中配置
 * 6.浏览器输入url
 *
 * 面试:Servlet的生命周期:
 * 1.调用init()方法,初始化(只调用一次)
 * 2.调用service()方法,处理客户端的请求(每次请求调用一次)
 * 3.调用destroy()方法,销毁(只调用一次)
 */

public class FirstServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        //初始化的方法可以利用ServletConfig来获取配置文件web.xml的数据(局部)
//        int page = Integer.parseInt(config.getInitParameter("page"));
        //获取全局的初始化参数
        int abc = Integer.parseInt(config.getServletContext().getInitParameter("abc"));
        System.out.println(abc);
    }

    //如果用户发送的语法是get请求,那么就会自动调用Servlet中的doGet()方法
    //例如,超链接
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器端向客户端响应的内容的类型(MIME)
        resp.setContentType("text/html;charset=utf-8");
        //向网页响应内容
        PrintWriter out = resp.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>servlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println(new Date());
        out.println("</body>");
        out.println("</html>");
    }
    //如果用户发送的语法是post请求,那么就会自动调用Servlet中的doPost()方法
    //例如,表单
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //向网页响应内容
        PrintWriter out = resp.getWriter();
        //request对象中的其他方法测试
        out.println("获取请求方法的名称:"+req.getMethod());
        out.println("获取项目访问的Application Context的名称:"+req.getContextPath());
        out.println("获取请求的URI地址:"+req.getRequestURI());
        //获取前端请求的参数 name="tom"&password=123456
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserService service = new UserServiceImpl();
        User user = service.isValidate(username,password);
        if (user != null){
            out.println("success......");
            out.println(username+"--------"+password);
        }else {
            out.println("error......");
        }
    }

}











